<template>
<div>
  {{obj}}
  <!-- <hr /> -->
  <!-- {{rules}} -->
  <el-form ref="dyform" :model="obj" :rules="rules" :label-width="config.forms.labelWidth">
    <el-form-item :prop="f.dataField" v-for="f in showFields" :label="f.name" :key="f.dataField">
      <template slot="label">
        {{f.name}} 
        <el-tooltip v-if="f.tooltip" class="item" effect="dark" :content="f.tooltip" placement="right-end">
          <i class="el-icon-info" style="color:#66b1ff"></i>
        </el-tooltip>
      </template>
      <!-- {{f}} -->
      <!-- <editor v-if="f.showType>0" :id="f.showType" v-model="f.showConfig"></editor> -->
      <!-- {{f.dataField}} -->
      <!-- {{f.dataType=='number'}} -->
      <component v-if="f.dataType=='number'" :is="getComponentById(f.showType)" v-bind="f.showConfig" v-model.number="obj[f.dataField]"></component>    
      <component v-else :is="getComponentById(f.showType)" v-bind="f.showConfig" v-model="obj[f.dataField]"></component>      
    </el-form-item>
  </el-form>  
  <el-button @click="submit">提交</el-button>
</div>
</template>

<script>
// 根据配置对象 渲染 表单页 的核心组件
import axios from 'axios'
import editor from '../editors/componentPropertiesEditor.vue'
export default {
  async created(){
    var rep= await axios.get("http://localhost:8811/api/ShowTypeComponente/GetAll")
    this.showTypes=rep.data.result
  },

  components:{editor},
  name:'formcomp',
  methods:{
    async init(){
      var url=this.config.initData.apiUrl
      var initDefaultValue=true
      // 有初始化api是编辑，没有是添加
      if(url){        
        initDefaultValue=false
        for (var k in this.$route.params){
          url=url.replace("{"+k+"}",this.$route.params[k])
        }      
        var rep
        if(this.config.initData.method=='GET'){
          rep=await axios.get(url)
        }
        else{
          rep=await axios.post(url)
        }        
        var result=rep.data[this.config.initData.dataField]        
        this.obj=result
        // console.log(this.obj);
      }
      for (var x in this.config.items){
        var item=this.config.items[x]
        var field=item.dataField
        var dataType=item.dataType
        var vali=item.rules;
        //初始化默认值
        if(initDefaultValue){
          switch(dataType){
            case 'string':
              // this.obj[field]=""
              this.$set(this.obj,field,"")
              break
            case 'number':
              this.$set(this.obj,field,0)
              break
            case 'bool':
              this.$set(this.obj,field,false)
              break
            case 'array':
              this.$set(this.obj,field,[])
              break
            case 'date':
              this.$set(this.obj,field,new Date())
          }
        }
        // 设置表单验证
        if(vali){          
          var vs=[]
          for (var y in vali){
            var v=vali[y]
            if(v.vali=='required')
            {
              vs.push({
                required: true,
                message:v.message,
                trigger:v.trigger
              })
            }
            else if(v.vali=='range')
            {
              vs.push({
                min:parseInt(v.min),
                max:parseInt(v.max),
                message:v.message,
                trigger:v.trigger
              })
            }
            else if(v.vali=='type')
            {
              if(v.type=='number'){
                //用正则
                vs.push({
                  validator:this.regexValidator,
                  pattern:"^[1-9]*[0-9]([\\.][0-9]*)?$",
                  message:v.message,
                  trigger:v.trigger
                })
              }
              else if (v.type=='integer'){
                //用正则
                vs.push({
                  validator:this.regexValidator,
                  pattern:"^\\d+$",
                  message:v.message,
                  trigger:v.trigger
                })
              }
              else{
                //date array
                vs.push({
                  type:v.type,
                  message:v.message,
                  trigger:v.trigger
                })  
              }              
            }
            else if(v.vali=='pattern')
            {
              vs.push({
                validator:this.regexValidator,
                pattern:v.pattern,
                message:v.message,
                trigger:v.trigger
              })
            }
            else if(v.vali=='custom')
            {
              vs.push({
                validator:this.customValidator,
                script:v.script,
                message:v.message,
                trigger:v.trigger
              })
            }
          }
          this.$set(this.rules,field,vs)
        }
      }
    },
    getComponentById(id){      
      if(this.showTypes!=null && this.showTypes.length>0){        
        return this.showTypes.filter(x=>x.id==id)[0].component
      }
      return ""
    },
    customValidator (rule, value, callback) {
      var scriptText=rule.script;      
      var func=eval(scriptText)
      var r=func(value)
      if(r){
        return callback()
      }else{
        return callback(new Error(rule.message))
      }
    },
    regexValidator(rule,value,callback){
      // console.log(rule.pattern);
      // var re=new RegExp(rule.pattern)
      // console.log(re);
      if (new RegExp(rule.pattern).test(value)){
        return callback()
      }
      else{
        return callback(new Error(rule.message))
      }      
    },
    async submit(){
      console.log('submit');
      this.$refs.dyform.validate(async v=>{
          console.log('vali result',v);
          if(v){
            console.log(this.obj);
            if(!this.isTest){
              var url=this.config.submitData.apiUrl
              for (var k in this.$route.params){
                url=url.replace("{"+k+"}",this.$route.params[k])
              } 
              if(this.config.submitData.method=='GET'){
              }
              else{
                var obj={}
                obj=this.obj
                for (var k in obj){
                  if(obj[k]==""){
                    var columns=this.config.items.filter(x=>x.dataField==k)
                    if(columns.length>0){
                      var col=columns[0]
                      var dataType=col.dataType
                      if(dataType=='number'){
                        obj[k]=null
                      }
                    }
                  }
                }
                var rep=await axios.post(url,obj)
                console.log("提交结果");
                console.log(rep);
                //todo 如何通知外面关闭弹框        
              }
              // console.log('emit ');
              //todo 改变路由到父级
              this.$root.$emit('closeDialog')
            }
            
          }
      })
      
    }
  },
  watch:{
    configa:{
      deep:true,
      handler(o,n){
        // while(this.showTypes.length<1){}
        this.config=this.configa
        this.init()
      }
    }
  },
  props:['configa','isTest'],
  computed:{
    showFields(){
      var all=this.config.items
      if(!all) return null
      var v=this.obj
      return all.filter(x=>{        
        if(x.if){
          var ifstr=x.if
          for (var k in v){
            ifstr=ifstr.replace("{"+k+"}",v[k])
          }
          // console.log(ifstr);
          try{
            return eval(ifstr)
          }
          catch{
            return false
          }
        }
        else{
          return true
        }
      })
    }
  },
  data(){    
    return {
      showTypes:[],
      obj:{
        
      },
      rules:{
        
      },
      config:{
        forms:{
          
        }
      }
    }
  }
}
</script>

<style>

</style>